package com.pronhub.cloud.shop.resolver;


import com.pronhub.cloud.shop.redis.MyRedisTemplate;
import com.pronhub.cloud.shop.domain.User;
import com.pronhub.cloud.shop.redis.MemberServerKeyPrefix;
import com.pronhub.cloud.shop.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class UserMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private MyRedisTemplate myRedisTemplate;
    //参数是否需要有当前处理类解析.
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //什么时候才由UserMethodArgumentResolver解析参数
        //1.参数类型是User
        //2.在参数类型上贴了@RedisValue
        return parameter.getParameterType()== User.class && parameter.getParameterAnnotation(RedisValue.class)!=null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //System.err.println("自定义的================");
        //怎么处理User类型？
        //1.获取Cookie，Request对象
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = CookieUtil.getCookie(request, CookieUtil.TOKEN_NAME);
        if(StringUtils.isEmpty(token)){
            //请求中没有token
            return null;
        }
        return myRedisTemplate.get(MemberServerKeyPrefix.USER_TOKEN,token,User.class);
    }
}
